package com.mmall.concurrency.syncContainer;

import com.mmall.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@NotThreadSafe
public class VoctorUnsafe2 {

    // Exception in thread "main" java.util.ConcurrentModificationException
    //	at java.util.Vector$Itr.checkForComodification(Vector.java:1184)
    private static void test1(Vector<Integer> vector){//foreach
        // 知识点 ： integer有equals方法。 int 没有
        for ( Integer v1 : vector){
            if (v1.equals(3)){
                vector.remove(v1);
            }
        }
    }

    // 迭代器的使用
    private static void test2(Vector<Integer> vector){
        Iterator<Integer> iterator = vector.iterator();
        while (iterator.hasNext()){
            Integer i = iterator.next();
            if (i.equals(3)){
                vector.remove(i);
            }
        }
    }

    // 正常单线程的for循环
    private static void test3(Vector<Integer> vector){
        for (Integer i = 0; i< vector.size();i++){
            if (vector.get(i).equals(3)){
                vector.remove(i);
            }
        }
    }

    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        vector.add(1);
        vector.add(2);
        vector.add(3);
        test3(vector);


    }

}
